#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <thread>
#include <mutex>
#include <fstream>
#include <ctime>
#include <json/json.h>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#include <curl/curl.h>
#include <sqlite3.h>
#include "http_client.h"

typedef websocketpp::server<websocketpp::config::asio> server;
typedef server::message_ptr message_ptr;

void log_message(const std::string& message) {
    std::time_t now = std::time(0);
    char* dt = std::ctime(&now);
    if (dt) {
        dt[strlen(dt)-1] = '\0'; // Remove newline
        std::cout << "[" << dt << "] " << message << std::endl;
    }
}

class AIRolePlayServer {
private:
    server ws_server;
    sqlite3* db;
    std::mutex db_mutex;
    std::map<std::string, Json::Value> character_profiles;

public:
    AIRolePlayServer() {
        ws_server.set_access_channels(websocketpp::log::alevel::all);
        ws_server.clear_access_channels(websocketpp::log::alevel::frame_payload);
        ws_server.init_asio();

        ws_server.set_message_handler([this](websocketpp::connection_hdl hdl, message_ptr msg) {
            this->on_message(hdl, msg);
        });

        init_database();
        init_characters();
    }
